<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\CourseSourceClass;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class CourseSourceClassController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new CourseSourceClass(), function (Grid $grid) {
            $grid->model()->orderByDesc('id');
            $grid->column('id');
            $grid->column('name');
            $grid->column('sort');
            $grid->column('created_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();

                $filter->equal('id')->width(3);
                $filter->like('name')->width(3);
                $filter->between('created_at')->datetime()->width(3);
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new CourseSourceClass(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('sort');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new CourseSourceClass(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->number('sort')->default(0);

            $form->saving(function (Form $form) {
                $id = $form->getKey();

                $exists = \App\Models\CourseSourceClass::where('name', $form->name)
                    ->when($id, function ($q) use ($id) {
                        return $q->where('id', '<>', $id);
                    })->exists();

                if ($exists) return $form->response()->error('名称已存在');
            });

            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
